package com.smartum.mpr.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.smartum.mpr.exception.DatabaseIntegrityException;
import com.smartum.mpr.exception.NotCorrectPermission;
import com.smartum.mpr.exception.NotExistsTypeException;
import com.smartum.mpr.model.Type;
import com.smartum.mpr.model.UploadedImageType;

@Repository
public class UploadedImageTypeDao extends GenericDao<Long, UploadedImageType> {


	public Type getType(Long userId, Long imageId) throws NotExistsTypeException, DatabaseIntegrityException{
		DetachedCriteria criteria = DetachedCriteria.forClass(UploadedImageType.class);
		criteria.createCriteria("user").add(Restrictions.eq("id", userId));
		criteria.createCriteria("image").add(Restrictions.eq("id", imageId));

		List types = hibernateTemplate.findByCriteria(criteria);

		if (types.size() == 0) {
			throw new NotExistsTypeException();
		} else if (types.size() > 1) {
			throw new DatabaseIntegrityException("database has few equals types");
		} else if (types.size() == 1) {
			return (Type) types.get(0);
		} else {
			throw new DatabaseIntegrityException();
		}
	}


	@Override
	protected Class<UploadedImageType> getEntityClass() {
		return UploadedImageType.class;
	}

}
